//
//  YPScrollView.m
//  YPScrollView
//
//  Created by lanou3g on 15/12/15.
//  Copyright © 2015年 王艳苹. All rights reserved.
//

#import "YPScrollView.h"

@interface YPScrollView ()<UIScrollViewDelegate>
@property (nonatomic,strong) UIScrollView *myScroll;
@property (nonatomic,strong) UIPageControl *myPage;

@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic,assign) NSInteger curentIndex;
@property (nonatomic,strong) NSMutableArray *contentViews;
@property (nonatomic,assign) NSInteger countNum;
@end
@implementation YPScrollView
//初始化方法本地图片
- (instancetype)initWithFrame:(CGRect)frame images:(NSArray<NSString*>*)array{
    self = [self initWithFrame:frame];
    if (self) {
        self.myScroll = [[UIScrollView alloc]initWithFrame:frame];
        self.myScroll.pagingEnabled = YES;
        self.myScroll.bounces = NO;
        self.myScroll.showsHorizontalScrollIndicator = NO;
        self.myScroll.contentSize = CGSizeMake(self.frame.size.width * 3 , self.frame.size.height);
        self.myScroll.contentOffset = CGPointMake(self.frame.size.width, 0);
        [self addSubview:_myScroll];
        self.myPage = [[UIPageControl alloc]initWithFrame:CGRectMake(0, frame.size.height - 20, frame.size.width, 20)];
        self.myPage.backgroundColor = [UIColor blackColor];
        [self addSubview:self.myPage];
        [self getImagesArrayByURLArray:array finish:^(NSArray *arrImage) {
            self.countNum = arrImage.count;
            self.myPage.numberOfPages = self.countNum;
            NSMutableArray *tempArr = @[].mutableCopy;
            for (int i = 0; i < arrImage.count; i++) {
                UIImageView *myImage = [[UIImageView alloc]initWithFrame:self.frame];
                myImage.image = arrImage[i];
                [tempArr addObject:myImage];
            }
            self.indexBlock = ^UIImageView*(NSInteger index){
                return tempArr[index];
            };
        }];
        [self addTimer];
        self.myScroll.delegate = self;
        [self bringSubviewToFront:self.myPage];
        self.curentIndex = 0;
    }
    return self;
}
- (void)addTimer{
    if(self.timer){
        return;
    }
    self.timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
}
//时间循环
- (void)timerAction:(NSTimer*)sender{
    CGPoint newOffset = CGPointMake(self.myScroll.contentOffset.x + CGRectGetWidth(self.frame),0);
    [self.myScroll setContentOffset:newOffset animated:YES];
    self.myPage.currentPage = self.curentIndex;
}
- (void)setContenView{
    NSInteger preNum = [self getIndexByCurentIndex:self.curentIndex - 1];
    NSInteger nextNum = [self getIndexByCurentIndex:self.curentIndex + 1];
    if (_contentViews == nil) {
        _contentViews = @[].mutableCopy;//初始化数组
    }
    [self.contentViews removeAllObjects];//删除掉所有的元素
    //重新装入到数组中的元素
    if (self.indexBlock) {
        [self.contentViews addObject:self.indexBlock(preNum)];
        [self.contentViews addObject:self.indexBlock(_curentIndex)];
        [self.contentViews addObject:self.indexBlock(nextNum)];
    }
}
- (void)setView{
    //执行移除子视图的方法
    [self.myScroll.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    //重新布局
    [self setContenView];
    NSInteger counter = 0;
    for (UIImageView *contentView in self.contentViews) {
        contentView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(contentViewTapAction:)];
        [contentView addGestureRecognizer:tapGesture];
        CGRect rightRect = contentView.frame;
        //      contentView.image = [UIImage imageNamed:@"loading.gif"];
        rightRect.origin = CGPointMake(self.frame.size.width * (counter++), 0);
        contentView.frame = rightRect;
        [self.myScroll addSubview:contentView];
    }
    [self.myScroll setContentOffset:CGPointMake(self.frame.size.width, 0)];
}
- (void)contentViewTapAction:(UITapGestureRecognizer*)sender{
    if (self.delegate && [self.delegate respondsToSelector:@selector(AddTapGesture:index:)]) {
        [self.delegate AddTapGesture:self index:self.curentIndex];
    }
}
//开始拖拽的时候
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.timer invalidate];
    self.timer = nil;
}
//拖拽结束的时候
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self addTimer];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    int contentOffsetX = scrollView.contentOffset.x;
    if(contentOffsetX >= (2 * CGRectGetWidth(self.frame))) {
        self.curentIndex = [self getIndexByCurentIndex:self.curentIndex + 1];
        NSLog(@"next当前页:%ld",(long)self.curentIndex);
        [self setView];
    }
    if(contentOffsetX <= 0) {
        self.curentIndex = [self getIndexByCurentIndex:self.curentIndex - 1];
        NSLog(@"previous当前页:%ld",(long)self.curentIndex);
        [self setView];
    }
}
//根据URL构造images数组
- (void)getImagesArrayByURLArray:(NSArray*)array finish:(void(^)(NSArray*))finish{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableArray *arrImage = @[].mutableCopy;
        for (NSString *str in array) {
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]];
            UIImage *image = [UIImage imageWithData:data];
            
            [arrImage addObject:image];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            finish(arrImage);
        });
    });
}
//getindex
- (NSInteger)getIndexByCurentIndex:(NSInteger)num{
    if (num == -1) {
        return self.countNum - 1;
    }else if(num == self.countNum){
        return 0;
    }else{
        return num;
    }
}
@end
